package cn.mengfly.testnrz.netty.decoder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.nio.charset.StandardCharsets;
import java.util.List;

public class StringIntegerHeaderDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception {
        // 判断是否消息头已经传输过来了
        if(buf.readableBytes() < 4) {
            return;
        }
        buf.markReaderIndex();
        // 取出消息头
        int length = buf.readInt();
        // 判断字符串消息是否都传输了过来
        if(buf.readableBytes() < length) {
            // 如果没有传输过来，将指针重新回滚到初始位置
            buf.resetReaderIndex();
            return;
        }
        byte[] inBytes = new byte[length];
        buf.readBytes(inBytes, 0, length);
        out.add(new String(inBytes, StandardCharsets.UTF_8));
    }
}